﻿var baseTreeUrl = CPWebRootPath + "/api/TreeEngine/GetTreeData";                    //获取树形列表url
var taskArray = [];
var points;
var timearr, temarr, humarr, temarr2, humarr2;   //时间、温度、湿度
var lushu;                              //百度地图路书
var ispause = false;                    //标识：更换开始暂停状态
var opptionstring;                      //左侧订单列表信息
var listnumstr;                         //订单数量信息
var tasklist;                           //用于存储所有任务编号
var arrcheck = [];                      //用于存储查找到的与搜索框中输入的字符串匹配的字符
var taskHistoryArr = new Array();      //用于存储所有任务的历史信息
var passPoint = new Array();           //经过点，数组格式

$(document).ready(function () {
    $("#allmap").height($(document).height() - 70);
    $("#menu-1").height($(document).height() - 70);
    $("#w-map-silder2").height($(document).height() - 70);
    //默认显示所有已完成任务信息
    showtask("","","");
});

$("#btnchecktask").click(function () {
    var taskCheck = $("#inputchecktask").val();
    var startdate = $("#fromdateinfo").val();         //开始时间
    var enddate = $("#todateinfo").val();             //结束时间 
    showtask(taskCheck, startdate, enddate);

})

/*左侧列表，显示所有已完成任务信息*/
function showtask(taskCheckOption, startTime, endTime) {
    var inputObj = new Object();
    inputObj.TreeCode = "Tree201811051712230001";
    inputObj.CurUserId = CPCurUserId;
    inputObj.CurUserIden = CPCurUserIden;
    var checkUrl = "?TaskId=" + taskCheckOption + "&leavetime=" + startTime + "&arriveTime=" + endTime
    var getUrl=baseTreeUrl + checkUrl;
   
    $.ajax({
        type: "POST",
        url: getUrl,
        data: JSON.stringify(inputObj),
        contentType: 'application/json',
        error: function (x, e) {
            // alert("未查询到数据！");
            $("#tasklist").html("");
            $("#ordercount").html(0);
        },
        success: function (result) { //回调函数，result，返回值
            if (result.Result == true) {
                taskArray = result.DataCol;
                //taskHistoryArr.push(taskArray);             //存储所有任务的信息
                $("#tasklist").html("");
                $("#ordercount").html(taskArray.length);
                //显示左侧列表中的任务编号
                $.each(taskArray, function (index, taskobj) {
                    var taskInfo = $.parseJSON(taskobj.DataRowJSON); //任务信息                    
                    var carArray = taskobj.items;                    //车辆信息
                    //拼接任务信息
                    opptionstring = ' <div class="panel panel-default clearfix" id="order' + index + '"> '
                        + '<div class="panel-heading">  '
                        + '  <a data-toggle="collapse" data-parent="#order' + index + '" href="#collapse' + index + '">   '
                        + '      <p class="pull-left w-orderll"><b>任务编号：' + taskInfo.TaskId + '</b></p> '
                        + '      <p class="pull-right  w-orderr" style="margin-right:-10px;">参运车辆：<span class="cor-blue" id="carcount' + index + '">' + carArray.length + '</span>辆</p> '
                        + '  </a> '
                        + '</div>'
                        + '</div>';
                    opptionstring += ' <div id="collapse' + index + '" class="panel-collapse collapse"></div>';
                    $("#tasklist").append(opptionstring);
                    //search(taskInfo.TaskId, index);              //根据任务编号查询历史信息，并显示车辆信息
                    //拼接车辆信息
                    $.each(carArray, function (carindex, va) {
                            var theCarInfo = $.parseJSON(va.DataRowJSON);
                            var carinfo = ' <div class="panel-group" id="accordion' + carindex + '"> '
                                + '  <div class="panel panel-default">'
                                + '      <div class="panel-heading"> '
                                + '          <h4 class="panel-title"> '
                                + '              <a data-toggle="collapse" data-parent="#accordion' + carindex + '" href="#carinfo' + carindex + '"> '
                                + '                  <div class="pull-left w-silder-titll"> '
                                + '                      <p class="pull-left cor-blue"><i class="iconfont  cor-blue">&#xe615;</i> <b>' + theCarInfo.CarNumber + '</b></p> '
                                + '                  </div>'
                                + '                  <div class="pull-right w-silder-titrr"> '
                                + '                      <p class="pull-left"><i class="iconfont text-success">&#xe60b;</i><em class="font-12"> 已完成</em></p>'
                                + '                  </div>'
                                + '             </a>'
                                + '          </h4>'
                                + '      </div> '
                                + '      <div id="carinfo' + carindex + '" class="panel-collapse collapse in"> '
                                + '          <div class="panel-body"> '
                                + '              <div class="w-threaa"> '
                                + '                  <div class="pull-left"><i class="iconfont w-icon">&#xe60d;</i>' + theCarInfo.MainDriverName + '  </div> '
                                + '                  <div class="pull-right font-12">  <p>车辆类型：'+theCarInfo.CodeTitle+'</p> </div> '
                                + '              </div> '
                                + '              <div class="w-threcc">'
                                + '                  <a href="" class="wn-active" id="' + carindex + '" onclick="replay(\'' + taskInfo.TaskId + '\',\'' + carindex + '\');return false;"><i class=" iconfont w-icon">&#xe612;</i> 追溯</a> '
                                + '                  <a href="" class="wn-active"  id="apause' + index + carindex + '" onclick="pause(\'' + index + carindex + '\');return false;"><i class=" iconfont w-icon">&#xe611;</i> 暂停</a><a id="over' + index + carindex + '" onclick="over(\'' + index + carindex + '\');return false;" href="">'
                                + ' <i class=" iconfont w-icon">&#xe613;</i> 结束</a>'
                                + '              </div>'
                                + '          </div>'
                                + '      </div>'
                                + '   </div>'
                                + '</div>';                           

                            $("#collapse" + index).append(carinfo);
                    });                   
                });
            }
        }
    });
}

//方法：查询sObj字符串是包含sFind字符串
function findLikeStr(sFind, sObj) {
    var nSize = sFind.length;
    var nLen = sObj.length;
    var sCompare;
    if (nSize <= nLen) {
        if (sFind == sObj) {
            return nSize;
            arrcheck.push(sFind);
        }
        for (var i = 0; i <= nLen - nSize + 1; i++) {
            sCompare = sObj.substring(i, i + nSize);
            if (sCompare == sFind) {
                return i;
                arrcheck.push(sFind);                        //将查询到的字符串放到数组中
            }
        }
    }
    return false;
}

//点击上方搜索按钮，查出相应订单（实现模糊查询）          改改改改改改
function checktask() {
    var checkstr = $("#inputchecktask").val();
    $("#tasklist").html("");
    var thenum = 0;                                           //表示查询到的订单数目
    //根据输入的订单编号进行查询，显示匹配的订单信息
    if (checkstr != "") {
        $.each(tasklist, function (index, number) {
            var iddd = findLikeStr(checkstr, number);
            if (iddd != false) {
                opptionstring = '<div class="panel panel-default clearfix" id="order' + index + '"> <div class="panel-heading"  <a data-toggle="collapse" data-parent="#order' + index + '" href="#collapse' + index + '">   <p class="pull-left w-orderll"><b>订单号：' + number + '</b></p>    <p class="pull-right  w-orderr">参运车辆：<span class="cor-blue" id="carcount' + index + '">1</span>辆</p>  </a>  </div> </div>';
                opptionstring += ' <div id="collapse' + index + '" class="panel-collapse collapse"></div>';
                $("#tasklist").append(opptionstring);
                search(number, index);
                thenum++;
            }
        });
        $("#ordercount").html(thenum);
    }
    //如果输入为空，则显示所有订单信息
    else {
        //alert("请输入订单编号进行查询");        
        $.each(tasklist, function (index, number) {
            opptionstring = '<div class="panel panel-default clearfix" id="order' + index + '"> <div class="panel-heading"  <a data-toggle="collapse" data-parent="#order' + index + '" href="#collapse' + index + '">   <p class="pull-left w-orderll"><b>订单号：' + number + '</b></p>    <p class="pull-right  w-orderr">参运车辆：<span class="cor-blue" id="carcount' + index + '">1</span>辆</p>  </a>  </div> </div>';
            opptionstring += ' <div id="collapse' + index + '" class="panel-collapse collapse"></div>';
            $("#tasklist").append(opptionstring);
            search(number, index);
            thenum++;
        });
        $("#ordercount").html(thenum);
    }

}

// 百度地图API功能
var map = new BMap.Map("allmap", { enableMapClick: false });
var point = new BMap.Point(116.404, 39.915);
map.centerAndZoom(point, 15);
map.enableScrollWheelZoom(true);

//添加路况信息控件
var ctrl = new BMapLib.TrafficControl({
    showPanel: false //是否显示路况提示面板
});
map.addControl(ctrl);
ctrl.setAnchor(BMAP_ANCHOR_BOTTOM_RIGHT);
//---------------------------------------------自定义控件---------------------------------------------
// 定义一个控件类,即function
function ZoomControl() {
    // 默认停靠位置和偏移量
    this.defaultAnchor = BMAP_ANCHOR_BOTTOM_RIGHT;
    this.defaultOffset = new BMap.Size(0, 0);
}

// 通过JavaScript的prototype属性继承于BMap.Control
ZoomControl.prototype = new BMap.Control();

// 自定义控件必须实现自己的initialize方法,并且将控件的DOM元素返回
// 在本方法中创建个div元素作为控件的容器,并将其添加到地图容器中
ZoomControl.prototype.initialize = function (map) {
    // 创建一个DOM元素
    var div = document.createElement("div");
    div.id = "main";                                                                                   //div "main"中显示历史数据的折线图
    div.style.height = "200px";
    div.style.width = "100%";
    div.style.visibility = "collapse";
    // 添加文字说明
    //div.appendChild(document.createTextNode("放大2级"));
    //div.innerHTML = "<img src=\"http://t2.baidu.com/it/u=351117335,2626617599&fm=0&gp=0.jpg\" />"
    // 设置样式
    //div.style.cursor = "pointer";
    //div.style.border = "1px solid gray";
    div.style.background = "black";
    //// 绑定事件
    //div.onclick = function (e) {
    //    //点击一次放大两级
    //    map.setZoom(map.getZoom() + 2);
    //    alert(1);
    //}
    // 添加DOM元素到地图中
    map.getContainer().appendChild(div);
    // 将DOM元素返回
    return div;
}
//// 创建控件
//var myZoomCtrl = new ZoomControl();
//// 添加到地图当中
//map.addControl(myZoomCtrl);


//调用相应任务编号中的数据，显示追溯过程
function replay(value, index) {
    map.clearOverlays();
    $("#main").remove(); 
    var hisPoints = new Array();
    // 创建控件
    var myZoomCtrl = new ZoomControl();
    // 添加到地图当中
    map.addControl(myZoomCtrl);

    var orderdata = null;
    var taskdata;
    //遍历所有任务的[历史信息]，找到此任务编号对应的[历史信息]，赋值给taskdata
    for (var i = 0; i < taskArray.length; i++) {
        var taskResult = taskArray[i];
        var taskInfo = $.parseJSON(taskResult.DataRowJSON); //任务信息 
        if (taskInfo.TaskId == value) {
            taskdata = taskArray[i];            
            break;
        }
    }  
    
    //得到车辆信息（传感器、GPS）
    var carArray = taskdata.items;
    var carInfo = carArray[index];
    var thecarInfo = $.parseJSON(carInfo.DataRowJSON);
    var snSensor = thecarInfo.SensorId;
    var snGPS = thecarInfo.GPSId;
    var startTime = thecarInfo.CarLeaveTime;
    var endTime = thecarInfo.CarArriveTime;
    startTime = startTime.replace(new RegExp("/", "g"), "-");
    endTime = endTime.replace(new RegExp("/", "g"), "-");

    //得到车辆运输的订单信息
    var orderArray = carInfo.items;
    var firstOrder = orderArray[0];                                 //第一个订单
    var thelastOrder = orderArray[orderArray.length - 1];           //最后一个订单
    var thelastOrderInfo = $.parseJSON(thelastOrder.DataRowJSON);
    var startstr = $.parseJSON(firstOrder.DataRowJSON).BaseName;    //起点：第一个订单的基地名称
    var startLon = $.parseJSON(firstOrder.DataRowJSON).longitude;   //起点：第一个订单的基地经度
    var startLat = $.parseJSON(firstOrder.DataRowJSON).latitude;    //起点：第一个订单的基地纬度
    var endstr = thelastOrderInfo.CustomerState + thelastOrderInfo.CustomerCity + thelastOrderInfo.CustomerDistrict + thelastOrderInfo.CustomerAddress;    //终点：最后一个订单的地址
    
    //显示规划路径
    var startPoint = new BMap.Point(startLon, startLat);
    var endAddress = endstr;
    //途径点
    $.each(orderArray, function (oindex, orderItem) {
        if (oindex < orderArray.length - 1) {
        var orderItemObj = $.parseJSON(orderItem.DataRowJSON);
        passPoint[oindex] = orderItemObj.CustomerState + orderItemObj.CustomerCity + orderItemObj.CustomerDistrict + orderItemObj.CustomerAddress; 
        }       
    });
    var driving = new BMap.DrivingRoute(map, { renderOptions: { map: map, autoViewport: true } });
    driving.search(startPoint, endAddress, { waypoints: passPoint});//waypoints表示途经点

    //startstr = "运输起点字符串超过十三个字符测试";
    //起点、终点的字符长度超过13，以省略号代替
    if (startstr.length > 13) {
        startstr = startstr.substring(0, 13) + "...";
    }
    if (endstr.length > 13) {
        endstr = endstr.substring(0, 13) + "...";
    }

    var div = document.getElementById("main");  //显示历史数据的div           
    div.style.visibility = "visible";
    //获取GPS数据，显示实际路线
    var markers = new Array();
    timearr = new Array();
    temarr = new Array();
    humarr = new Array();
    temarr2 = new Array();
    humarr2 = new Array();
    $.ajax({
        type: "GET",
        url: historyDataUrl + "?SN=SNS00005066&startTime=" + startTime + "&endTime=" + endTime,
        dataType: 'json',
        error: function (x, e) {
            alert("获取数据有误！");
        },
        async: true,
        beforeSend: function () {
            showMark();
        },
        success: function (result) {
            var json = result;
            var pntlist = json.datalist;//回调函数，result，返回值
            if (pntlist.length != 0) {
                var senlist = pntlist[0].valuelist;    //获取的数据值    
                var unitlist = pntlist[0].fielddim;       //单位数组
                var sensor;
                $.each(senlist, function (i, tinfo) {
                    sensor = tinfo.fieldvalue;
                    var lng, lat;        //传感器经纬度
                    var temperature1, temperature2, humidity1, humidity2, speed; //传感器实时温度、湿度、速度
                    var unitTem, unitHum, unitSpeed; //单位
                    temperature1 = sensor[0];
                    humidity1 = sensor[1];
                    temperature2 = sensor[2];
                    humidity2 = sensor[3];
                    lat = sensor[4];
                    lng = sensor[5];
                    speed = sensor[8];
                    unitTem = unitlist[0];
                    unitHum = unitlist[1];
                    unitSpeed = unitlist[8];                  
                    temarr.push(temperature1);
                    humarr.push(humidity1);
                    timearr.push(tinfo.time);
                    temarr2.push(temperature2);
                    humarr2.push(humidity2);
                    var point = new BMap.Point(lng, lat);
                    hisPoints.push(point);
                    var obj = new Object();
                    obj.lng = point.lng;
                    obj.lat = point.lat;
                    //obj.html = '<div id="detailinfo" class="w-map-pre" style="top: -170px; right: -140px;"></div>';

                    obj.html = '<div id="detailinfo" class="w-map-pre" style="top: -160px; right: -140px;"> <div class="w-locon-two ">  <div class="w-locon-twott">  <div class="twott-number" style="font-size:12px;">   <p>车牌号</p>    <p>' + thecarInfo.CarNumber + '</p> </div> <div class="twott-title" style="text-align: left;"> <p>起点：<b>' + startstr + '</b></p>   </div> <div class="twott-title" style="text-align: left;"><p>终点：<b>' + endstr + '</b></p>  </div>   </div>  <div class="w-locon-treeup">     <ul class="w-jclk2">  <li class="cor-red">  <p>' + temperature1 + unitTem + '</p> <p><i class="iconfont  font-30">&#xe605;</i></p>  <p class="cor-gre font-12">温度</p> </li> <li class="cor-purple"> <p>' + humidity1 + unitHum + '</p> <p><i class="iconfont  font-30 ">&#xe606;</i></p>    <p class="cor-gre font-12">湿度</p></li> <li class="cor-yellow "> <p>' + speed + unitSpeed + '</p>   <p><i class="iconfont  font-30">&#xe60f;</i></p>  <p class="cor-gre font-12">速度</p>  </li> </ul> <ul class="w-jclk2">  <li class="cor-red">  <p>' + temperature2 + unitTem + '</p> <p><i class="iconfont  font-30">&#xe605;</i></p>  <p class="cor-gre font-12">温度</p> </li> <li class="cor-purple"> <p>' + humidity2 + unitHum + '</p> <p><i class="iconfont  font-30 ">&#xe606;</i></p>    <p class="cor-gre font-12">湿度</p></li> <li class="cor-yellow "> <p>' + speed + unitSpeed +'</p>   <p><i class="iconfont  font-30">&#xe60f;</i></p>  <p class="cor-gre font-12">速度</p>  </li> </ul> </div> <div class="sanjiao"></div> </div> </div>';
                    obj.pauseTime = 0.5;
                    markers.push(obj);
                })
            }
        },
        complete: function () {
            hideMark();
            // 实例化一个驾车导航用来生成路线
            map.addOverlay(new BMap.Polyline(hisPoints, { strokeColor: '#111' }));
            map.setViewport(hisPoints);
            if (lushu != null) {
                lushu.pause();
            }
            lushu = new BMapLib.LuShu(map, hisPoints, {
                defaultContent: "",//"从天安门到百度大厦"
                autoView: true,//是否开启自动视野调整，如果开启那么路书在运动过程中会根据视野自动调整
                icon: new BMap.Icon('../../Plat/Monitor/img/bus.png', new BMap.Size(52, 36), { anchor: new BMap.Size(27, 13) }),
                speed: 8000,
                enableRotation: true,//是否设置marker随着道路的走向进行旋转
                landmarkPois: markers
            });
            setTimeout(function () { lushu.start(); }, 1000);
            setTimeout(function () { lushu.showInfoWindow(); }, 1500);

            showchart();
        }
    });  

   
}

//点击暂停
function pause(index) {
    var ap = document.getElementById("apause" + index);
    if (ispause) {
        lushu.start();
        lushu.showInfoWindow();
        ap.innerHTML = '<i class=" iconfont w-icon">&#xe611;</i> 暂停';
        ispause = false;
    } else if (!ispause) {
        lushu.pause();
        ap.innerHTML = '<i class=" iconfont w-icon">&#xe612;</i> 开始';
        ispause = true;
    }
}

//点击结束
function over(index) {
    $("#detailinfo").html("");
    map.clearOverlays();
    lushu.stop();
    $("#main").remove();
}
//显示遮罩层
function showMark() {
    $("#mask").height($(document).height());
    $("#mask").width($(document).width());
    $("#mask").html("<div id='maskText'>数据加载中,请稍后......</div>");
    $("#mask").css("line-height",$(document).height()+"px");
    $("#mask").show(); 
}
//隐藏遮罩层
function hideMark() {
    $("#mask").hide();
}

//折线图显示历史数据
function showchart() {
    // 路径配置
    require.config({
        paths: {
            echarts: 'http://echarts.baidu.com/build/dist'
        }
    });
    // 使用
    require(
        [
            'echarts',
            'echarts/chart/line' // 使用柱状图就加载bar模块，按需加载
        ],
        function (ec) {
            // 基于准备好的dom，初始化echarts图表
            var myChart = ec.init(document.getElementById('main'));

            var option = {
                title: {
                    text: '',
                    subtext: ''
                },
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: ['温度曲线1（℃）', '温度曲线2（℃）',"湿度曲线1（%）", "湿度曲线2（%）"],
                },
                toolbox: {
                    show: true,
                    feature: {
                        mark: { show: false },
                        dataView: { show: false, readOnly: false },
                        magicType: { show: false, type: ['line', 'bar'] },
                        restore: { show: false },
                        saveAsImage: { show: false }
                    }
                },
                calculable: true,
                xAxis: [
                    {
                        type: 'category',
                        boundaryGap: false,
                        data: timearr
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        axisLabel: {
                            formatter: '{value}'
                        }
                    },
                    {
                        type: 'value',
                        axisLabel: {
                            formatter: function (value) {
                                return value
                            }
                        }
                    },
                ],
                series: [
                    {
                        name: '温度曲线1（℃）',
                        type: 'line',
                        yAxisIndex: 1,
                        data: temarr,
                        markPoint: {
                            data: [
                                { type: 'max', name: '最大值' },
                                { type: 'min', name: '最小值' }
                            ]
                        },
                        //markLine: {
                        //    data: [
                        //        { type: 'average', name: '平均值' }
                        //    ]
                        //},
                        //itemStyle: {
                        //    normal: {
                        //        lineStyle: {
                        //            width: 0.1
                        //        }
                        //    }
                        //}
                    },
                    {
                        name: '温度曲线2（℃）',
                        type: 'line',
                        yAxisIndex: 1,
                        data: temarr2,
                        markPoint: {
                            data: [
                                { type: 'max', name: '最大值' },
                                { type: 'min', name: '最小值' }
                            ]
                        },                        
                    },
                    {
                        name: '湿度曲线1（%）',
                        type: 'line',
                        data: humarr,
                        markPoint: {
                            data: [
                                { type: 'max', name: '最大值' },
                                { type: 'min', name: '最小值' }
                            ]
                        },                        
                    },
                    {
                        name: '湿度曲线2（%）',
                        type: 'line',
                        data: humarr2,
                        markPoint: {
                            data: [
                                { type: 'max', name: '最大值' },
                                { type: 'min', name: '最小值' }
                            ]
                        },
                        
                    },
                ]
            };
            // 为echarts对象加载数据 
            myChart.setOption(option);
        }
    );
}

//获取日期
Date.prototype.DateAdd = function (strInterval, Number) {
    var dtTmp = this;
    switch (strInterval) {
        case 's': return new Date(Date.parse(dtTmp) + (1000 * Number));
        case 'n': return new Date(Date.parse(dtTmp) + (60000 * Number));
        case 'h': return new Date(Date.parse(dtTmp) + (3600000 * Number));
        case 'd': return new Date(Date.parse(dtTmp) + (86400000 * Number));
        case 'w': return new Date(Date.parse(dtTmp) + ((86400000 * 7) * Number));
        case 'q': return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number * 3, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
        case 'm': return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
        case 'y': return new Date((dtTmp.getFullYear() + Number), dtTmp.getMonth(), dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
    }
};
function GetDateStr(AddDayCount) {
    var dd = new Date();
    var ddd = dd.DateAdd('d', AddDayCount);
    var y = ddd.getFullYear();
    var m = ddd.getMonth() + 1;              //获取当前月 
    var d = ddd.getDate();
    var h = ddd.getHours();
    var n = ddd.getMinutes();
    var s = ddd.getSeconds();
    return y + "-" + m + "-" + d + " " + h + ":" + n + ":" + s;
}


